package com.banmao.mall.service.client.impl;

import com.banmao.mall.mapper.*;
import com.banmao.mall.model.bo.client.goods.GoodsListBO;
import com.banmao.mall.model.pojo.Foorprint;
import com.banmao.mall.model.vo.client.goods.*;
import com.banmao.mall.model.vo.client.index.*;
import com.banmao.mall.model.vo.client.index.GrouponVO;
import com.banmao.mall.service.client.GoodsService;
import com.banmao.mall.util.CustomUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Service("cGoodsServiceImpl")
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    GrouponMapper grouponMapper;
    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    AdMapper adMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    TopicMapper topicMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    IssueMapper issueMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    @Autowired
    FoorprintMapper foorprintMapper;

    @Value("${myimage.baseURL}")
    private String imageBaseURL;

    @Override
    public HomeIndexVO index() {

        // 获取新品信息（is_new == true）
        List<NewGoodsVO> newGoodsVOS = goodsMapper.selectNewGoods();
        // 处理图片前缀
        for (NewGoodsVO newGoodsVO : newGoodsVOS) {
            if(newGoodsVO.getPicUrl() != null) {
                if(!newGoodsVO.getPicUrl().startsWith("http")) {
                    newGoodsVO.setPicUrl(imageBaseURL + newGoodsVO.getPicUrl());
                }
            }
        }

        //将过期的优惠券状态更改
        couponMapper.alterOutDateCouponStatus();
        // 获取优惠券信息（查前三张）
        List<CouponVO> couponVOS = couponMapper.selectAllCoupon();

        // 获取商品一级类目
        List<ChannelVO> channelVOS = categoryMapper.selectChannel();
        // 处理图片前缀
        for (ChannelVO channelVO : channelVOS) {
            if(channelVO.getIconUrl() != null) {
                if(!channelVO.getIconUrl().startsWith("http")) {
                    channelVO.setIconUrl(imageBaseURL + channelVO.getIconUrl());
                }
            }
        }

        // 获取团购信息
        List<GrouponVO> groupGoodsVOS = goodsMapper.selectByGroupon();

        // 获取推广信息
        List<BannerVO> bannerVOS = adMapper.selectAllAd();
        // 处理图片路径前缀
        for (BannerVO bannerVO : bannerVOS) {
            if(bannerVO.getUrl() != null) {
                if(!bannerVO.getUrl().startsWith("http")) {
                    bannerVO.setUrl(imageBaseURL = bannerVO.getUrl());
                }
            }
        }

        // 获取品牌商信息（前四个）
        List<BrandVO> brandVOS = brandMapper.selectFourBrand();
        // 处理图片路径前缀
        for (BrandVO brandVO : brandVOS) {
            if(brandVO.getPicUrl() != null) {
                if(!brandVO.getPicUrl().startsWith("http")) {
                    brandVO.setPicUrl(imageBaseURL = brandVO.getPicUrl());
                }
            }
        }

        // 获取人气商品
        List<HotGoodsVO> hotGoodsVOS = goodsMapper.selectHotGoods();
        // 处理图片路径前缀
        for (HotGoodsVO hotGoodsVO : hotGoodsVOS) {
            if(hotGoodsVO.getPicUrl() != null) {
                if(!hotGoodsVO.getPicUrl().startsWith("http")) {
                    hotGoodsVO.setPicUrl(imageBaseURL + hotGoodsVO.getPicUrl());
                }
            }
        }

        // 获取Topic（前四个）
        List<TopicVO> topicVOS = topicMapper.selectFourTopic();
        // 处理图片路径前缀
        for (TopicVO topicVO : topicVOS) {
            if(topicVO.getPicUrl() != null) {
                if(!topicVO.getPicUrl().startsWith("http")) {
                    topicVO.setPicUrl(imageBaseURL + topicVO.getPicUrl());
                }
            }
        }

        // 获取FloorGoods，根据一级类目获取前四个商品
        ArrayList<FloorGoodsVO> floorGoodsVOS = new ArrayList<>();
        // 遍历一级类目
        for (ChannelVO channelVO : channelVOS) {
            FloorGoodsVO floorGoodsVO = new FloorGoodsVO();
            List<GoodsVO> goodsVOS = goodsMapper.selectFloorGoods(channelVO.getId());
            // 处理图片路径
            for (GoodsVO goodsVO : goodsVOS) {
                if(goodsVO.getPicUrl() != null) {
                    if(!goodsVO.getPicUrl().startsWith("http")) {
                        goodsVO.setPicUrl(imageBaseURL + goodsVO.getPicUrl());
                    }
                }
            }

            floorGoodsVO.setId(channelVO.getId());
            floorGoodsVO.setName(channelVO.getName());
            floorGoodsVO.setGoodsList(goodsVOS);

            floorGoodsVOS.add(floorGoodsVO);
        }

        HomeIndexVO homeIndexVO = new HomeIndexVO();
        homeIndexVO.setNewGoodsList(newGoodsVOS);
        homeIndexVO.setCouponList(couponVOS);
        homeIndexVO.setChannel(channelVOS);
        homeIndexVO.setGrouponList(groupGoodsVOS);
        homeIndexVO.setBanner(bannerVOS);
        homeIndexVO.setBrandList(brandVOS);
        homeIndexVO.setHotGoodsList(hotGoodsVOS);
        homeIndexVO.setTopicList(topicVOS);
        homeIndexVO.setFloorGoodsList(floorGoodsVOS);

        return homeIndexVO;
    }

    @Override
    public int goodsCount() {

        Integer totalCount = goodsMapper.selectTotalCount();

        return totalCount;
    }

    @Override
    public GoodsCategoryVO goodsCategory(Integer id) {

        // 首先根据ID查找类目
        CategoryVO categoryVO = categoryMapper.selectCategoryByID(id);

        GoodsCategoryVO goodsCategoryVO = new GoodsCategoryVO();

        // 判断该类目是一级类目还是二级类目
        if(categoryVO.getPid() == 0) {
            // 是一级类目，放入parentCategory
            goodsCategoryVO.setParentCategory(categoryVO);
            // 根据一级类目的ID查找该一级类目的子类目
            List<CategoryVO> childrenCategory = categoryMapper.selectChildrenByPID(categoryVO.getId());
            // 将子类目的集合放入brotherCategory
            goodsCategoryVO.setBrotherCategory(childrenCategory);
            if (childrenCategory.size() != 0) {
                // 将子类目的第一个child放入currentCategory
                goodsCategoryVO.setCurrentCategory(childrenCategory.get(0));
            }
        } else {
            // 是二级类目，放入currentCategory
            goodsCategoryVO.setCurrentCategory(categoryVO);
            // 根据该二级类目的PID查找父类目
            CategoryVO parentCategory = categoryMapper.selectCategoryByID(categoryVO.getPid());
            // 将父类目放入parentCategory
            goodsCategoryVO.setParentCategory(parentCategory);
            // 根据父类目的ID查找其子类目
            List<CategoryVO> childrenCategory = categoryMapper.selectChildrenByPID(parentCategory.getId());
            // 将所有子类目放入brotherCategory
            goodsCategoryVO.setBrotherCategory(childrenCategory);
        }

        // 处理图片路径前缀
        CategoryVO currentCategory = goodsCategoryVO.getCurrentCategory();
        if (currentCategory != null) {
            if(currentCategory.getPicUrl() != null) {
                if(!currentCategory.getPicUrl().startsWith("http")) {
                    currentCategory.setPicUrl(imageBaseURL + currentCategory.getPicUrl());
                }
            }
            if(currentCategory.getIconUrl() != null) {
                if(!currentCategory.getIconUrl().startsWith("http")) {
                    currentCategory.setIconUrl(imageBaseURL + currentCategory.getIconUrl());
                }
            }
        }

        CategoryVO parentCategory = goodsCategoryVO.getParentCategory();
        if(parentCategory != null) {
            if(parentCategory.getPicUrl() != null) {
                if(!parentCategory.getPicUrl().startsWith("http")) {
                    parentCategory.setPicUrl(imageBaseURL + parentCategory.getPicUrl());
                }
            }
            if(parentCategory.getIconUrl() != null) {
                if(!parentCategory.getIconUrl().startsWith("http")) {
                    parentCategory.setIconUrl(imageBaseURL + parentCategory.getIconUrl());
                }
            }
        }

        List<CategoryVO> brotherCategory = goodsCategoryVO.getBrotherCategory();
        if(brotherCategory != null && brotherCategory.size() != 0) {
            for (CategoryVO vo : brotherCategory) {
                if(vo.getPicUrl() != null) {
                    if(!vo.getPicUrl().startsWith("http")) {
                        vo.setPicUrl(imageBaseURL + vo.getPicUrl());
                    }
                }
                if(vo.getIconUrl() != null) {
                    if(!vo.getIconUrl().startsWith("http")) {
                        vo.setIconUrl(imageBaseURL + vo.getIconUrl());
                    }
                }
            }
        }

        return goodsCategoryVO;
    }

    @Override
    public GoodsListVO goodsList(GoodsListBO goodsListBO) {

        PageHelper.startPage(goodsListBO.getPage(), goodsListBO.getSize());

        List<GoodsVO> goodsVOS = goodsMapper.selectGoodsByCategoryIDorBrandID(goodsListBO);

        // 处理图片路径前缀
        for (GoodsVO goodsVO : goodsVOS) {
            if(goodsVO.getPicUrl() != null) {
                if(!goodsVO.getPicUrl().startsWith("http")) {
                    goodsVO.setPicUrl(imageBaseURL + goodsVO.getPicUrl());
                }
            }
        }

        PageInfo<GoodsVO> goodsVOPageInfo = new PageInfo<>(goodsVOS);
        long totalCount = goodsVOPageInfo.getTotal();

        GoodsListVO goodsListVO = new GoodsListVO();
        goodsListVO.setCount(totalCount);
        goodsListVO.setGoodsList(goodsVOS);

        // 通过类目ID查找
        if (goodsListBO.getKeyword() == null && goodsListBO.getCategoryId() != null) {
            if (goodsListBO.getCategoryId() != 0) {
                // 根据该二级类目的PID查找父类目
                CategoryVO parentCategory = categoryMapper.selectCategoryByChildID(goodsListBO.getCategoryId());
                // 根据父类目的ID查找其子类目
                List<CategoryVO> childrenCategory = categoryMapper.selectChildrenByPID(parentCategory.getId());
                // 处理filterCategoryList中的图片路径前缀
                handleCategoryVOImageURL(childrenCategory);
                // 将所有子类目放入filterCategoryList
                goodsListVO.setFilterCategoryList(childrenCategory);
            } else {
                // 查找所有二级类目
                List<CategoryVO> categoryVOS = categoryMapper.selectChildrenByPID(goodsListBO.getCategoryId());
                // 处理filterCategoryList中的图片路径前缀
                handleCategoryVOImageURL(categoryVOS);
                // 将所有子类目放入filterCategoryList
                goodsListVO.setFilterCategoryList(categoryVOS);
            }

        } else {
            List<CategoryVO> categoryVOS = new ArrayList<>();
            // 查找品牌商下所有商品的二级类目
            for (GoodsVO goodsVO : goodsVOS) {
                CategoryVO categoryVO = categoryMapper.selectCategoryByGoods(goodsVO.getCategoryId());

                // 处理图片路径前缀
                if(categoryVO.getIconUrl() != null) {
                    if(!categoryVO.getIconUrl().startsWith("http")) {
                        categoryVO.setIconUrl(imageBaseURL + categoryVO.getIconUrl());
                    }
                }
                if(categoryVO.getPicUrl() != null) {
                    if(!categoryVO.getPicUrl().startsWith("http")) {
                        categoryVO.setPicUrl(imageBaseURL + categoryVO.getPicUrl());
                    }
                }

                // 过滤相同的类目
                if(!categoryVOS.contains(categoryVO)) {
                    categoryVOS.add(categoryVO);
                }
            }
            // 处理filterCategoryList中的图片路径前缀
            handleCategoryVOImageURL(categoryVOS);
            // 将所有类目放入filterCategoryList
            goodsListVO.setFilterCategoryList(categoryVOS);

            if(goodsListBO.getKeyword() != null) {
                // 即 keyword != null
                // 根据关键字查找后，将关键字添加入搜索历史中
                // 先获得用户ID，如果没有登陆，则不存储
                Integer userId = null;
                try {
                    userId = CustomUtils.judgeUserLogin();
                } catch (IllegalAccessException e) {
                    //e.printStackTrace();
                }
                if(userId != null) {
                    // 得到UserId
                    // 检查搜索历史表里有无相同keyword，有则更新updateTime，无则添加
                    int result = searchHistoryMapper.selectCountWithKeyword(userId, goodsListBO.getKeyword());
                    if(result != 0) {
                        // 在该用户的搜索例历史中存在相同的keyword
                        // 更新updateTime
                        result = searchHistoryMapper.updateUpdateTime(userId, goodsListBO.getKeyword());
                    } else {
                        // 否则添加记录
                        // 将keywords放入搜索历史
                        result = searchHistoryMapper.insertHistory(userId, goodsListBO.getKeyword());
                    }
                }
            }
        }

        return goodsListVO;
    }

    private void handleCategoryVOImageURL(List<CategoryVO> categoryVOS) {
        // 处理图片路径前缀
        for (CategoryVO categoryVO : categoryVOS) {
            if(categoryVO.getPicUrl() != null) {
                if(!categoryVO.getPicUrl().startsWith("http")) {
                    categoryVO.setPicUrl(imageBaseURL + categoryVO.getPicUrl());
                }
            }
            if(categoryVO.getIconUrl() != null) {
                if(!categoryVO.getIconUrl().startsWith("http")) {
                    categoryVO.setIconUrl(imageBaseURL + categoryVO.getIconUrl());
                }
            }
        }
    }

    @Override
    public GoodsDetailVO goodsDetail(Integer goodsId) {

        // 获取specification信息
        List<SpecificationVO> specificationVOS = goodsSpecificationMapper.selectByGoodsID(goodsId);
        if (specificationVOS != null) {
            for (SpecificationVO specificationVO : specificationVOS) {
                List<ValueVO> valueList = specificationVO.getValueList();
                if(valueList != null) {
                    for (ValueVO valueVO : valueList) {
                        if(valueVO != null) {
                            if (valueVO.getPicUrl() != null) {
                                if(!valueVO.getPicUrl().startsWith("http")) {
                                    valueVO.setPicUrl(imageBaseURL + valueVO.getPicUrl());
                                }
                            }
                        }
                    }
                }
            }
        }

        // 获取groupon信息
        List<GrouponRulesVO> grouponRulesVOS = grouponRulesMapper.selectByGoodsID(goodsId);

        // 获取issue信息
        List<IssueVO> issueVOS = issueMapper.selectAllIssue();

        // 获取userHasCollect的值
        // 获取当前的用户
        Integer userId = null;
        try {
            userId = CustomUtils.judgeUserLogin();
        } catch (IllegalAccessException e) {
            //e.printStackTrace();
        }

        Integer collectCount;
        if (userId != null) {
            collectCount = collectMapper.selectCountByUserIDAndGoodsID(userId, goodsId);
        } else {
            collectCount = 0;
        }

        // 获取comment的信息（前三个）
        List<CommentDataVO> commentDataVO = commentMapper.selectByGoodsID(goodsId);
        // 处理图片路径前缀
        for (CommentDataVO dataVO : commentDataVO) {
            if(dataVO != null) {
                if(dataVO.getAvatar() != null && !dataVO.getAvatar().startsWith("http")) {
                    dataVO.setAvatar(imageBaseURL + dataVO.getAvatar());
                }
                if(dataVO.getPicList() != null) {
                    String[] picList = dataVO.getPicList();
                    for (int i = 0; i < picList.length; i++) {
                        if(picList[i] != null && !picList[i].startsWith("http")) {
                            picList[i] = imageBaseURL + picList[i];
                        }
                    }
                }
            }
        }
        // 获取comment的总数
        Integer commentTotalCount = commentMapper.selectCountByGoodsID(goodsId);

        CommentVO commentVO = new CommentVO();
        commentVO.setCount(commentTotalCount);
        commentVO.setData(commentDataVO);

        // 获取attribute的信息
        List<AttributeVO> attributeVOS = goodsAttributeMapper.selectByGoodsID(goodsId);

        // 获取info的信息
        InfoVO infoVO = goodsMapper.selectInfoByID(goodsId);
        if(infoVO.getPicUrl() != null) {
            if(!infoVO.getPicUrl().startsWith("http")) {
                infoVO.setPicUrl(imageBaseURL + infoVO.getPicUrl());
            }
        }
        for (int i = 0; i < infoVO.getGallery().length; i++) {
            String gallery = infoVO.getGallery()[i];
            if(gallery != null) {
                if(!gallery.startsWith("http")) {
                    gallery = imageBaseURL + gallery;
                    infoVO.getGallery()[i] = gallery;
                }
            }

        }

        // 获取shareImage的值
        String shareImage = infoVO.getShareUrl();

        // 获取brand的信息
        BrandVO brandVO = brandMapper.selectByBrandID(infoVO.getBrandId());

        // 获取product的信息
        List<ProductVO> productVOS = goodsProductMapper.selectByGoodsID(goodsId);

        // 将所有结果封装起来
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        goodsDetailVO.setSpecificationList(specificationVOS);
        goodsDetailVO.setGroupon(grouponRulesVOS);
        goodsDetailVO.setIssue(issueVOS);
        goodsDetailVO.setUserHasCollect(collectCount);
        goodsDetailVO.setShareImage(shareImage);
        goodsDetailVO.setComment(commentVO);
        goodsDetailVO.setAttribute(attributeVOS);
        goodsDetailVO.setBrand(brandVO);
        goodsDetailVO.setProductList(productVOS);
        goodsDetailVO.setInfo(infoVO);

        return goodsDetailVO;
    }

    @Override
    public GoodsRelatedVO goodsRelated(Integer goodsId)  {

        // 获取统一类目下的相关商品（除去当前商品的前四个）
        // 随机获取
        List<GoodsVO> goodsVOS = goodsMapper.selectRelatedByGoodsID(goodsId);

        GoodsRelatedVO goodsRelatedVO = new GoodsRelatedVO();
        goodsRelatedVO.setGoodsList(goodsVOS);


        //xu 添
        Foorprint foorprint = new Foorprint();
        Integer userId = (Integer) SecurityUtils.getSubject().getSession().getAttribute("userId");
        if(userId!=null){
            Foorprint foorprint1 = foorprintMapper.selectByGoodsId(goodsId,userId);
            if(foorprint1==null){
                foorprint.setUserId(userId);
                foorprint.setGoodsId(goodsId);
                foorprint.setAddTime(new Date());
                foorprint.setUpdateTime(new Date());
                foorprint.setDeleted(false);
                int insert = foorprintMapper.insert(foorprint);
            }else{
                foorprint1.setUpdateTime(new Date());
                foorprintMapper.updateByPrimaryKey(foorprint1);
            }

        }

        return goodsRelatedVO;
    }
}
